<template>
	<!-- <base-loading-box :loading="loading" :isEmpty="isEmpty" :error="error">	</base-loading-box> -->
	<div
		class="w-full rounded-[10px] relative mx-auto mb-5 z-[1]"
		:style="{
			width: isSelected ? screenWidth + 'px' : 'auto',
			maxWidth: !isSelected ? '1390px' : '100%'
		}">
		<div
			ref="screen_wrap"
			class="w-full bg-[#0e1224e6] rounded-t-[10px]"
			:style="{
				height: isSelected ? 'calc(100vh - 110px)' : screenHeight + 'px'
			}">
			<!-- <div
					v-show="!loaded"
					v-if="!loading"
					class="absolute top-0 left-0 rounded-t-[10px] z-10 right-0 bottom-[50px] bg-[rgba(0,0,0,.5)] flex items-center justify-center">
					<play-dialog
						ref="play_dialog"
						@loaded="handleLoaded"
						@collect="handCollect"
						:backUrl="backUrl"
						:data="gameDetail"
						:firstLoad="firstLoad"
						:type="type" />
				</div> -->
			<div
				v-if="isShowDialog"
				class="absolute top-0 left-0 rounded-t-[10px] z-10 right-0 bottom-[50px] bg-[#0e1224e6] flex items-center justify-center">
				<Dialog
					:data="data"
					:currency="gameCurrency"
					@enterGame="handleEnterGame"
					@currencyChange="handleCurrencyChange"></Dialog>
			</div>
			<div
				v-if="loadingIframe"
				class="absolute top-0 left-0 rounded-t-[10px] z-9 right-0 bottom-[50px] flex items-center justify-center">
				<base-loading-box :loading="true" :isEmpty="true"></base-loading-box>
			</div>
			<div class="h-full overflow-hidden rounded-t-[10px]" id="iframe_wrap" ref="iframe_wrap">
				<img
					class="w-full object-cover animate-scale-opacity"
					v-if="!accountStore.isLogin"
					:src="data?.gameIcon" />
			</div>
		</div>
		<tool-bar
			:type="type"
			:currentTab="playType"
			:data="data"
			:currency="gameCurrency"
			@currencyChange="handleToolBarCurrenctChange"
			@changePlayType="changePlayTypeToolbar"
			@collect="handCollect"
			@toMovie="handleMovie"
			@fullScreen="handleFull" />
	</div>
	<Description :data="data" :winnerData="winnerData"></Description>
	<GameError @close="handleClose" :modelValue="showErrorDialog" :errType="errType" :type="type" />
</template>
<script lang="ts" setup>
import { onMounted, ref, watch, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ToolBar from './tool-bar.vue'
import Dialog from './dialog.vue'
import Description from './description.vue'
import { useRequest } from '@/hooks'
// import BaseLoadingBigIcon from '@/components/base/loading-big-icon/index.vue'
import { AccountShowType } from '@/types'
import { useSearchGameStore } from '@/store'
import { BaseLoadingBox } from '@/components/base'
// import { getGameDetail } from '@/api/slots'

import { useSlotStore, useCasinoStore, useAccountStore, useAppStore, useWalletStore } from '@/store'
import { isPC } from '@/utils'
import { launchGameAPI, getGameDetailBySlug, getGameDetailWinner } from '@/api/other.ts'
import { useDialog } from '@/hooks'
import { useElementSize } from '@vueuse/core'
import GameError from '../dialog/game-error.vue'

const searchGameStore = useSearchGameStore()

const loaded = ref(false)
const router = useRouter()
const errType = ref('region')
const iframe_wrap: any = ref(null)
const loading = ref(false)
const screen_wrap: any = ref(null)
const loadingIframe = ref(false)
const firstLoad = ref(false)
const isSelected = ref(false)
const playType = ref('play')
const dialog = useDialog()
const slotStore = useSlotStore()
const casinoStore = useCasinoStore()
const accountStore = useAccountStore()
const appStore = useAppStore()
const showErrorDialog = ref(false)

const gameCurrency = ref('')
const winnerData = ref({})
const walletStore = useWalletStore()
const route = useRoute()
const isShowDialog = ref(true)
const gameInfo = ref()

const emits = defineEmits(['update:data'])

const props = defineProps({
	type: {
		type: String,
		default: 'slots'
	}
})

const { width: screeWidth, height } = useElementSize(screen_wrap)

const screenHeight = computed(() => {
	let limit = 1440
	if (isPC()) {
		limit = 720
	}

	return (screeWidth.value / 1280) * limit
})

const screenWidth = computed(() => {
	return (height.value / 720) * 1280
})

const backUrl = computed(() => {
	return location.origin + '/' + props.type
})

const gameDetail = computed(() => {
	if (props.type === 'casino') {
		return casinoStore.gameDetail
	}
	return slotStore.gameDetail
})

watch(
	() => route.params.id,
	(val) => {
		loaded.value = false
		firstLoad.value = false
		//loadingIframe.value = false
		if (val) {
			initData()
		}
	}
)

watch(
	() => accountStore.isLogin,
	() => {
		initData()
	}
)

watch(
	() => [walletStore.walletConfig.selectedFiatCurrency, appStore.lang],
	() => {
		initData()
	}
)
const { run, data } = useRequest<any>(getGameDetailBySlug)
onMounted(() => {
	initData()
	window.addEventListener('message', quitGame)
})

const quitGame = (e: any) => {
	if (e.data.type === 'Window.Redirect' && e.data.url === backUrl.value) {
		router.push('/slots')
	}
}
const initData = () => {
	searchGameStore.hide()
	gameCurrency.value = walletStore.walletConfig.selectedFiatCurrency
	getData()
	getWinnerData()
	appStore.setGaming(true)
}
const getData = async () => {
	loading.value = true
	await run({ slug: route.params.id })
	emits('update:data', data.value)

	let isFunMode = accountStore.isLogin ? false : true
	initGame(isFunMode)
}
const getWinnerData = async () => {
	winnerData.value = {}
	const result = await getGameDetailWinner({ slug: route.params.id })
	winnerData.value = result.data
}
const initGame = async (isFunMode: boolean) => {
	if (accountStore.isLogin) {
		isShowDialog.value = true
		loadingIframe.value = true
		const result = (await launchGameAPI({
			gameCode: data.value?.gameCode,
			walletCurrency: walletStore.balanceCur?.currency ?? 'USDT',
			gameCurrency: gameCurrency.value,
			device: isPC() ? 'DESKTOP' : 'MOBILE',
			funMode: isFunMode,
			referrer: window.location.href
		})) as any
		gameInfo.value = result.data
		iframeLoadGame(result.data, true)
		loadingIframe.value = false
	}
}

const handleIframeLoad = (val: any) => {
	console.log(val.currentTarget.contentWindow.location)
	setTimeout(() => {
		loadingIframe.value = false
	}, 1000)
}

const changePlayTypeToolbar = (val: any) => {
	let isFunMode = val === 'demo' ? true : false

	if (accountStore.isLogin) {
		enterGame(isFunMode)
	} else {
		accountStore.showAccount(AccountShowType.register)
	}
}
const handleCurrencyChange = (val: any) => {
	gameCurrency.value = val
	initGame(false)
}
const handleToolBarCurrenctChange = (val: any) => {
	gameCurrency.value = val
	if (isShowDialog.value) {
		initGame(false)
	} else {
		enterGame(false)
	}
}

const handCollect = async () => {
	if (props.type === 'casino') {
		const params = {
			eid: gameDetail.value.eid,
			action: gameDetail.value.favoriteState
		}
		if (gameDetail.value.favoriteState) {
			dialog.warning({
				titleT: 'slotsall.cancelCollect',
				contentT: 'slotsall.collectConfirm',
				confirmTextT: 'action.confirm',
				cancelTextT: 'action.cancel',
				confirmFn: async () => {
					await casinoStore.cancelCollectGame(params)
					casinoStore.gameDetail.favoriteState = !casinoStore.gameDetail.favoriteState
				},
				cancelFn: () => {
					console.log('cancel')
				}
			})
		} else {
			await casinoStore.collectGame(params)
			casinoStore.gameDetail.favoriteState = !casinoStore.gameDetail.favoriteState
		}
	} else {
		const params = {
			id: slotStore.gameDetail.id,
			gameId: slotStore.gameDetail.gameId,
			cancelFlag: slotStore.gameDetail.collectState
		}
		if (slotStore.gameDetail.collectState) {
			dialog.warning({
				titleT: 'slotsall.cancelCollect',
				contentT: 'slotsall.collectConfirm',
				confirmTextT: 'action.confirm',
				cancelTextT: 'action.cancel',
				confirmFn: async () => {
					await slotStore.cancelCollectGame(params)
					slotStore.gameDetail.collectState = !slotStore.gameDetail.collectState
				},
				cancelFn: () => {
					console.log('cancel')
				}
			})
		} else {
			await slotStore.collectGame(params)
			slotStore.gameDetail.collectState = !slotStore.gameDetail.collectState
		}
	}
}

const handleFull = () => {
	if (screen_wrap.value) {
		fullscreen(screen_wrap.value)
	}
}

function fullscreen(element: any) {
	if (!document.fullscreenEnabled) {
		return Promise.reject(new Error('全屏模式被禁用'))
	}
	let result = null
	if (element.requestFullscreen) {
		result = element.requestFullscreen()
	} else if (element.mozRequestFullScreen) {
		result = element.mozRequestFullScreen()
	} else if (element.msRequestFullscreen) {
		result = element.msRequestFullscreen()
	} else if (element.webkitRequestFullscreen) {
		result = element.webkitRequestFullScreen()
	}
	isShowDialog.value = false
	return result || Promise.reject(new Error('不支持全屏'))
}

const handleMovie = (val: boolean) => {
	isSelected.value = val
	const app_content = document.getElementById('app_content')
	if (val && app_content) {
		app_content.style.paddingTop = '0px'
	}
	if (!val && app_content) {
		app_content.style.paddingTop = '20px'
	}
}

const handleClose = () => {
	showErrorDialog.value = false
}
const iframeLoadGame = (result: any, isFirstLoad: boolean) => {
	let iframe: any = document.documentElement.querySelector('#iframe')
	if (iframe) {
		iframe_wrap.value.removeChild(iframe)
	}
	iframe = document.createElement('iframe')
	iframe.setAttribute('id', 'iframe')
	iframe.setAttribute('frameborder', '0')
	iframe.setAttribute('tabindex', '0')
	iframe.setAttribute('scrolling', 'yes')
	iframe.style.display = 'block'
	iframe.width = '100%'
	iframe.height = '100%'
	iframe_wrap.value.appendChild(iframe)
	iframe.src = result.game_url

	iframe.onload = handleIframeLoad
	if (!isFirstLoad) {
		isShowDialog.value = false
	}
}
const handleEnterGame = async (isFunMode: boolean) => {
	if (accountStore.isLogin) {
		if (isFunMode) {
			//模拟
			enterGame(isFunMode)
		} else {
			if (isPC()) {
				isShowDialog.value = false
			} else {
				location.href = gameInfo.value.game_url
			}
		}
	} else {
		accountStore.showAccount(AccountShowType.register)
	}
}
const enterGame = async (isFunMode: boolean) => {
	isShowDialog.value = false
	let iframe: any = document.documentElement.querySelector('#iframe')
	iframe.src = ''
	loadingIframe.value = true
	const result = (await launchGameAPI({
		gameCode: data.value.gameCode,
		walletCurrency: walletStore.balanceCur?.currency ?? 'USDT',
		gameCurrency: gameCurrency.value,
		device: isPC() ? 'DESKTOP' : 'MOBILE',
		funMode: isFunMode,
		referrer: window.location.href
	})) as any
	if (isPC()) {
		iframeLoadGame(result.data, false)
	} else {
		location.href = result.data.game_url
	}
}
onUnmounted(() => {
	appStore.setGaming(false)
	const app_content = document.getElementById('app_content')
	if (app_content) {
		app_content.style.paddingTop = '20px'
	}

	window.removeEventListener('message', quitGame)
})
</script>
<style lang="scss" scoped>
#iframe_wrap {
	:deep(#iframe) {
		border-top-left-radius: 10px;
		border-top-right-radius: 10px;
	}
}
</style>
